package com.wch.SpringBootTestDemo.webservice.config;


import javax.xml.ws.Endpoint;

import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.wch.SpringBootTestDemo.webservice.service.DemoWebService;
import com.wch.SpringBootTestDemo.webservice.service.impl.DemoWebServiceImpl;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration 
public class CxfConfig {
	
	@Bean
	public ServletRegistrationBean dispatcherServlet(){
		return new ServletRegistrationBean(new CXFServlet(),"/WebServiceTest/*");
		
	}

	@Bean(name = Bus.DEFAULT_BUS_ID)
	public SpringBus springBus(){
		return new SpringBus();
	}
	
	@Bean
	public DemoWebService demoWebService(){
		return new DemoWebServiceImpl();
	}
	
	@Bean
	public Endpoint endpoint(){
		EndpointImpl endpoint = new EndpointImpl(springBus(), demoWebService());
        endpoint.publish("/api");
        return endpoint;		

	}

	/**
	 * 集成webservice之后，webservice服务发布成功，其他http接口无法正常访问,
	 * 原因是springboot默认注册的是 dispatcherServlet，
	 * 当手动配置 ServletRegistrationBean后不会再去注册默认的   dispatcherServlet，
	 * 所以需要手动去注册一个dispatcherServlet，
	 * @return
	 */
	@Bean
	public ServletRegistrationBean restServlet() {
		//注解扫描上下文
		AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
		applicationContext.scan("com.wch.SpringBootTestDemo");            //项目包名
		DispatcherServlet rest_dispatcherServlet = new DispatcherServlet(applicationContext);
		ServletRegistrationBean registrationBean = new ServletRegistrationBean(rest_dispatcherServlet);
		registrationBean.setLoadOnStartup(1);
		registrationBean.addUrlMappings("/*");
		return registrationBean;
	}

}
